//
//  MerchantDetailsViewController.m
//  UI_HLJ_Frame
//
//  Created by dllo on 15/7/7.
//  Copyright (c) 2015年 毕宏伟. All rights reserved.
//

#import "MerchantDetailsViewController.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "MerchantDetailePackageModel.h"
#import "MerchantDetailePackageTableViewCell.h"
#import "MerchantAllPackageViewController.h"
#import "MerchantDescTableViewCell.h"
#import "PackageDetailsViewController.h"

#import "MBProgressHUD.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface MerchantDetailsViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, retain)UIView *headView;
@property(nonatomic ,retain)UITableView  *tableView;
@property(nonatomic,retain)UIView *titleView;
@property(nonatomic ,retain)NSMutableArray * tableViewArr;
@property(nonatomic,retain)NSString *label;
@property(nonatomic, retain)NSMutableArray *arr;

// 右上角按钮的属性
@property(nonatomic, assign)BOOL isArchiver;


// 简介
@property(nonatomic, retain)NSDictionary *desc;

// 小菊花
@property(nonatomic,retain)MBProgressHUD *hud;
@end

@implementation MerchantDetailsViewController

- (void)dealloc
{
    [_merchantIdStr release];
    [_coverStr release];
    [_addressStr release];
    [_nameStr release];
    [_logoStr release];
    [_headView release];
    [_tableView release];
    [_titleView release];
    [_tableViewArr release];
    [_label release];
    [_desc release];
    [_mer release];
    [_merchant release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详情";
   
    [self fanguidang];

    self.navigationController.navigationBar.translucent=NO;
    
    self.hud = [[MBProgressHUD alloc] init];
    [self.view addSubview:self.hud];
    [self.hud show:YES];
    self.hud.labelText = @"loading...";
    
    
    [self createData];
    
    
    
    self.title = @"💎 商 家 💎";
    
    UIBarButtonItem *bar=[[UIBarButtonItem alloc]initWithTitle:@"back" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem=bar;
    
    self.headView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height/2)];
    self.headView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *titleImage = [[UIImageView alloc]initWithFrame:CGRectMake(40, self.view.frame.size.height/2*2/3-30, self.view.frame.size.width/3.5, 80)];
    [titleImage sd_setImageWithURL:[NSURL URLWithString:self.logoStr]];
    titleImage.layer.masksToBounds=YES;
    titleImage.layer.cornerRadius=30;
    
    UILabel *labler = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2.35, HEIGHT/2.87, WIDTH / 3 * 1.6, 50)];
    labler.numberOfLines = 0;
//    labler.backgroundColor = [UIColor orangeColor];
    labler.text=self.nameStr;
    
    UILabel *lableraddress = [[UILabel alloc]initWithFrame:CGRectMake(40, HEIGHT/2.32, WIDTH / 3 * 2, 40)];
    lableraddress.text=self.addressStr;
    lableraddress.font =[UIFont systemFontOfSize:14];
    lableraddress.numberOfLines=0;

    // 解析数据中图片数据为null时写一个判断,当为null时用一张图片代替,当有数据图片时将图片显示

    

    UIImageView  * image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/2*2/3)];
    if ([self.coverStr isKindOfClass:[NSNull class]]) {
        UIImage *image1 = [UIImage imageNamed:@"关于图"];
        [image initWithImage:image1];
    }else{
//        [image sd_setImageWithURL:[NSURL URLWithString:self.coverStr]];
        [image sd_setImageWithURL:[NSURL URLWithString:self.coverStr] placeholderImage:[UIImage imageNamed:@"占位图"]];
        
    }
  
    
    [self.headView addSubview:image];
    [image addSubview:titleImage];
    [self.headView addSubview:labler];
    [self.headView addSubview:lableraddress];
    [self.view addSubview:self.headView];

    
    
    
    
    
        self.tableViewArr = [NSMutableArray array];
    

    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

#pragma mark 右上角按钮
    UIButton *buttonYou = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonYou.frame = CGRectMake(0, 0, 30, 30);
    if (self.isArchiver) {
        [buttonYou setImage:[UIImage imageNamed:@"tubiao1"] forState:UIControlStateNormal];
    } else{
        [buttonYou setImage:[UIImage imageNamed:@"tubiao2"] forState:UIControlStateNormal];
    }
    [buttonYou addTarget:self action:@selector(clickYou:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonYou];
}

- (void)crteaTableView
{
    self.tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableView.tableHeaderView =self.headView;
    self.tableView.delegate=self;
    self.tableView.dataSource =self;
    
    
    [self.view addSubview:self.tableView];
}




#pragma mark 归档
- (void)clickYou:(UIButton *)button{
    
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
    NSString *sandBoxPath = sandBox[0];
    NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"ShangPin.plist"];
    
    self.arr = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
    
    if (self.isArchiver) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已取消收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        
        NSInteger index = 0;
        for (NSInteger i = 0; i < self.arr.count; i++) {
            NewMerchantModel *vie = self.arr[i];
            if ([vie.name isEqualToString:self.nameStr]) {
                index = i;
                break;
            }
        }
        [self.arr removeObjectAtIndex:index];
        
        // 对已经修改过的数组,再次进行归档操作
        NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
        NSString *sandBoxPath = sandBox[0];
        NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"ShangPin.plist"];
//        NSLog(@"%@",documentPath);
        
        // 根据对应的路径进行归档操作
        [NSKeyedArchiver archiveRootObject:self.arr toFile:documentPath];
        
        [button setImage:[UIImage imageNamed:@"tubiao2.png"] forState:UIControlStateNormal];
        self.isArchiver = NO;
        
    } else {
        
        NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
        NSString *sandBoxPath = sandBox[0];
        NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"ShangPin.plist"];
        
        if (self.arr != nil) {
            [self.arr addObject:self.mer];
            
        } else {
            self.arr = [NSMutableArray array];
            [self.arr addObject:self.mer];
        }
        
        // 根据对应的路径进行归档操作
        [NSKeyedArchiver archiveRootObject:self.arr toFile:documentPath];
        
        self.isArchiver = YES;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        
        [button setImage:[UIImage imageNamed:@"tubiao1.png"] forState:UIControlStateNormal];
        
        
//        NSLog(@"%@", documentPath);
        
    }
}
#pragma mark 反归档
- (void)fanguidang{
    
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
    NSString *sandBoxPath = sandBox[0];
    
    // 拼接
    NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"ShangPin.plist"];
    self.arr = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
//    NSLog(@"%@", documentPath);
    
    self.isArchiver = NO;
    if (self.arr != nil) {
    
        for (NewMerchantModel *new in self.arr) {
            if ([new.name isEqualToString:self.nameStr]) {
                self.isArchiver = YES;
                break;
            }
        }
    }
    
}

- (void)createData
{
    

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[NSString stringWithFormat:@"http://hunliji.com/v2/api/app/merchants/%@/works.json?page=1&per_page=5&kind=set_meal", self.merchantIdStr] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *worksArr = dic[@"works"];
        NSString *work_count = dic[@"works_count"];
       
        for (NSDictionary *tempDic in worksArr) {
            self.merchant = [[MerchantDetailePackageModel alloc] init];
            [self.merchant setValuesForKeysWithDictionary:tempDic];
            [self.tableViewArr addObject:self.merchant];
            [_merchant release];
        }
       
        self.label = [NSString stringWithFormat:@"共%@个套餐", work_count];

        AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
        NSString *str111 =[NSString stringWithFormat:@"http://hunliji.com/v1/api/app/merchants/%@.json", self.merchantIdStr];
        [manager1 GET:str111 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic = responseObject;
            self.desc = dic[@"merchant"];
            
            [self.tableView reloadData];
            
            [self crteaTableView];
            
            [self.hud hide:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
//        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        if (section ==0) {
            
            self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
            self.titleView.backgroundColor = [UIColor colorWithRed:1.000 green:0.503 blue:0.713 alpha:1.000];
            UILabel *leftLabel =[[UILabel alloc]initWithFrame:CGRectMake(10,1,120, 30)];
            leftLabel.text = self.label;
            leftLabel.center=CGPointMake(self.view.frame.size.width/2, 20);
            [self.titleView addSubview:leftLabel];
            
            [_titleView release];
            return self.titleView;
            
        }
        else if (section==1)
        {
            self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
            self.titleView.backgroundColor = [UIColor whiteColor];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame=CGRectMake(0, 0, 120, 30);

//            button.layer.borderWidth = 1;
            button.layer.cornerRadius = 15;
            [button setTitle:@"显示全部" forState:UIControlStateNormal];

            [button setTitle:@"显示全部" forState:UIControlStateNormal]; 

            [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            button.layer.masksToBounds =YES;
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
            button.backgroundColor =[UIColor colorWithRed:1.000 green:0.404 blue:0.651 alpha:1.000];
            button.center=CGPointMake(self.view.frame.size.width/2, 20);
            [self.titleView addSubview:button];
            
            [_titleView release];
            return self.titleView;
        }
        
        else if (section==2)
        {
            self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
            self.titleView.backgroundColor = [UIColor colorWithRed:1.000 green:0.503 blue:0.713 alpha:1.000];
            UILabel *leftLabel =[[UILabel alloc]initWithFrame:CGRectMake(10,1,120, 30)];
            leftLabel.text = @"简介";
            
            [self.titleView addSubview:leftLabel];
                            [_titleView release];
            return self.titleView;
            
        }
        
        else
        {
            return nil;
        }
    }
    
    


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger section = indexPath.section;
    if (section==0) {
        return 100;
    }else if(section==1){
        return 150;
    }
    else if(section == 2){
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil];
        // 根据文本计算高度,限制一个文本的最大范围(375,0)
        // 第二个属性作用:指定一个属性来定义对应文本和字体所占用的高度
        CGRect rect = [self.desc[@"desc"] boundingRectWithSize:CGSizeMake(355, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height ;
    }else{
        return 0;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 30;
    }else if(section==1){
        return 40;
    }
    else{
        return 30;
    }

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return self.tableViewArr.count;
    }else if (section == 2){
        
        if ([self.desc[@"desc"] isKindOfClass:[NSNull class]]) {
            return 0;
        }else{
        return 1;
        }
        
    }else if(section == 1){
        return 0;
    }else{
        return 0;
    }

}
-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    if (section == 0) {
        static NSString * reuse= @"reuse";
        MerchantDetailePackageModel *model = self.tableViewArr[indexPath.row];
        MerchantDetailePackageTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[MerchantDetailePackageTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        
        [cell.merchantImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_path]];
        cell.title.text=model.title;
        cell.collectors_count.text=[NSString stringWithFormat:@"收藏:%@",model.collectors_count];
        cell.actual_price.text=[NSString stringWithFormat:@"￥%@",model.actual_price];
        cell.actual_price.textColor = [UIColor redColor];
        return cell;
    }else if (section == 2){
        static NSString *reuse1 = @"reuse1";
        MerchantDescTableViewCell *merchantDescTableViewCell = [tableView dequeueReusableCellWithIdentifier:reuse1];
        if (!merchantDescTableViewCell) {
            merchantDescTableViewCell = [[MerchantDescTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse1];
            merchantDescTableViewCell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        merchantDescTableViewCell.desc.text = self.desc[@"desc"];
        merchantDescTableViewCell.desc.font = [UIFont systemFontOfSize:15];
        return merchantDescTableViewCell;
    }else{
        return nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
    // Dispose of any resources that can be recreated.
}
-(void)click:(UIButton *)button{
    
    MerchantAllPackageViewController *allVC=[[MerchantAllPackageViewController alloc]init];
    [self.navigationController pushViewController:allVC animated:YES];
    
    
    allVC.bid = [NSString stringWithFormat:@"%@",self.merchantIdStr];
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section == 0) {
        PackageDetailsViewController *packageDetailsViewController = [[PackageDetailsViewController alloc] init];
        MerchantDetailePackageModel *model = self.tableViewArr[indexPath.row];
        packageDetailsViewController.idStr = (NSNumber *)model.bid;
        
        [self.navigationController pushViewController:packageDetailsViewController animated:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
